package com.yk._02多线程消费差;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;

public class _01传统的消费差的写法 {
    public static void main(String[] args) {

        Resource resource = new Resource();
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                resource.producer();
            }
        }, "生产线程").start();
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                resource.consumer();
            }
        }, "消费线程").start();
    }
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Resource{

    private int num = 0;

    @SneakyThrows
    public synchronized void producer() {
        while (num != 0) {//这里不能写 if 否则会出现虚假唤醒
            this.wait();
        }
        num++;
        System.err.println(Thread.currentThread().getName() + " 生产成功 num=" + num);
        this.notifyAll();
    }

    @SneakyThrows
    public synchronized void consumer() {
        while (num == 0) {//这里不能写 if 否则会出现虚假唤醒
            this.wait();
        }
        num--;
        System.out.println(Thread.currentThread().getName() + " 消费成功 num=" + num);
        this.notifyAll();
    }


}
